package org.jetlinks.demo.protocol.siterwell.tcp.util;



import org.apache.commons.lang.StringUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by LL.
 * For：字符串处理
 */

public class ByteUtils {
    /**
     * 组合数组
     *
     * @param first
     * @param second
     * @param <T>
     * @return
     */
    public static <T> byte[] concat(byte[] first, byte[] second) {
        byte[] result = Arrays.copyOf(first, first.length + second.length);
        System.arraycopy(second, 0, result, first.length, second.length);
        return result;
    }

    /**
     * 不够位数的在前面补0，保留num的长度位数字
     *
     * @param code
     * @return
     */
    public static String autoGenericCode(String code, int num) {
        String result = "";
        // 保留num的位数
        // 0 代表前面补充0
        // num 代表长度
        // d 代表参数为正数型
        result = String.format("%0" + num + "d", Integer.parseInt(StringUtils.isBlank(code) ? "0" : code));

        return result;
    }

    /**
     * 不够位数的在前面补0，保留num的长度位数字
     *
     * @param code
     * @return
     */
    public static String autoGenericCode(int code, int num) {
        String result = "";
        // 保留num的位数
        // 0 代表前面补充0
        // num 代表长度
        // d 代表参数为正数型
        result = String.format("%0" + num + "d", code);

        return result;
    }


    /**
     * str 原字符串
     * strLength 字符串总长
     */
    public static String addZeroForNum(String str, int strLength, boolean isLeft) {
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                if (isLeft) {
                    sb.append("0").append(str);// 左补0
                } else {
                    sb.append(str).append("0");//右补0
                }
                str = sb.toString();
                strLen = str.length();
            }
        }

        return str;
    }

    /**
     * 获取字符串的字节长度,中文按2字节算
     * @param chstring
     * @return
     */
    public static int length(String chstring) {
        int length = 0;
        if(null == chstring || chstring.equals("") || chstring.length() == 0)
            return 0;
        for(int i = 0; i < chstring.length(); i++) {
            char c = chstring.charAt(i);
            if(isChinese(c)) {
                length += 2;
            } else {
                length += 1;
            }
        }
        return length;
    }

    /**
     * 判断字符是不是中文字符
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        int ascii = (int)c;
        if(ascii >= 0 && ascii <= 255)
            return false;
        return true;
    }

    /**
     * 字符串转16进制字符串
     *
     * @param str
     * @return
     */
    public static String str2HexStr(String str) {

        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;

        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }
        return sb.toString().trim();
    }

    /**
     * 十六进制转换字符串
     *
     * @param hexStr Byte字符串(Byte之间无分隔符 如:[616C6B])
     * @return String 对应的字符串
     */
    public static String hexStr2Str(String hexStr) {
        if (StringUtils.isBlank(hexStr)) {
            return null;
        }
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;

        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * bytes转换成十六进制字符串
     *
     * @param b byte数组
     * @return String 每个Byte值之间空格分隔
     */
    public static String byte2HexStr(byte[] b) {
        if (b == null) {
            return null;
        }
        String stmp = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
        }
        return sb.toString().toUpperCase().trim();
    }

    /**
     * 字符串数组转16进制
     *
     * @param b
     * @return
     */
    public static String byte2HexStr(String[] b) {
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < b.length; n++) {
            sb.append(byteToHex(Byte.valueOf(b[n])));
        }
        return sb.toString().toUpperCase().trim();
    }

    /**
     * 字符串数组转16进制
     *
     * @param b
     * @return
     */
    public static String byte2ByteStr(byte[] b) {
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < b.length; n++) {
            sb.append(b[n]);
            sb.append(',');
        }
        return sb.toString();
    }

    /**
     * 字符串数组转16进制
     *
     * @param b
     * @return
     */
    public static byte[] hexStrToHexArr(String[] b) {
        byte[] hexArr = new byte[b.length];
        for (int n = 0; n < b.length; n++) {
            hexArr[n] = Byte.valueOf(b[n]);
        }
        return hexArr;
    }

    public static byte[] hexStrToHexArr(String byteStr) {
        return hexStrToHexArr(byteStr.split(","));
    }

    /**
     * 字节字符串转16进制
     *
     * @param byteStr
     * @return
     */
    public static String byte2HexStr(String byteStr) {
        return byte2HexStr(byteStr.split(","));
    }


    /**
     * hex转byt[]
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;

    }

    /**
     * 字节转hex
     *
     * @param b
     * @return
     */
    public static String byteToHex(byte b) {
        return ("" + "0123456789ABCDEF".charAt(0xf & b >> 4) + "0123456789ABCDEF".charAt(b & 0xf));
    }

    static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }


    public static String trim(String num) {
        String newStr = num.replaceAll("^(0+)", "");
        return newStr;
    }

    /**
     * byte 转无符号 int
     *
     * @param data
     * @return
     */
    public static Integer byteToUnsignedInt(byte data) {
        return data & 0xff;
    }


    /**
     * 获取单个bit值
     * <p>
     * b为传入的字节，i为第几位（范围0-7），
     * 如要获取bit0，则i=0
     *
     * @param b
     * @param i
     * @return
     */
    public int getBit(byte b, int i) {
        int bit = (int) ((b >> i) & 0x1);
        return bit;
    }

    /**
     * 将byte转换为一个长度为8的byte数组，数组每个值代表bit
     */
    public static byte[] getBooleanArray(byte b) {
        byte[] array = new byte[8];
        for (int i = 7; i >= 0; i--) {
            array[i] = (byte) (b & 1);
            b = (byte) (b >> 1);
        }
        return array;
    }

    /**
     * 把byte转为字符串的bit
     */
    public static String byteToBit(byte b) {
        return ""
                + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
                + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
                + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
                + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
    }

    /**
     * int 获取两位hex
     *
     * @param number
     * @return
     */
    public static String intT2Hex(int number) {
        String hex = "";
        if (number < 16) {
            hex = "000" + Integer.toHexString(number);
        } else if (number <= 255 && number > 16) {
            hex = "00" + Integer.toHexString(number);
        } else if (number > 255) {
            hex = Integer.toHexString(number);
            if (hex.length() < 4) {
                hex = "0" + hex;
            }
        }
        return hex;
    }


    /**
     * byte数组转成字符串
     */
    public static String btye2Str(byte[] data) {
        String str = new String(data);
        return str;
    }


    /**
     * 将byte数组转化成浮点数（4个字节带小数的浮点数）
     */
    public static float byte2int_float(byte b[]) {
        int bits = b[3] & 0xff | (b[2] & 0xff) << 8 | (b[1] & 0xff) << 16
                | (b[0] & 0xff) << 24;

        int sign = ((bits & 0x80000000) == 0) ? 1 : -1;
        int exponent = ((bits & 0x7f800000) >> 23);
        int mantissa = (bits & 0x007fffff);

        mantissa |= 0x00800000;
        // Calculate the result:
        float f = (float) (sign * mantissa * Math.pow(2, exponent - 150));

        return f;
    }

    /**
     * 将十六进制串转化为byte数组
     */
    public static final byte[] hex2byte(String hex) throws IllegalArgumentException {
        if (hex.length() % 2 != 0) {
            throw new IllegalArgumentException();
        }
        char[] arr = hex.toCharArray();
        byte[] b = new byte[hex.length() / 2];
        for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
            String swap = "" + arr[i++] + arr[i];
            int byteint = Integer.parseInt(swap, 16) & 0xFF;
            b[j] = new Integer(byteint).byteValue();
        }
        return b;
    }

    /**
     * 将十六进制串转换为二进制
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 将字符串转成ASCII值
     */
    public static String strToASCII(String data) {
        String requestStr = "";
        for (int i = 0; i < data.length(); i++) {
            char a = data.charAt(i);
            int aInt = (int) a;
            requestStr = requestStr + integerToHexString(aInt);
        }
        return requestStr;
    }

    /**
     * 将十进制整数转为十六进制数，并补位
     */
    public static String integerToHexString(int s) {
        String ss = Integer.toHexString(s);
        if (ss.length() % 2 != 0) {
            ss = "0" + ss;//0F格式
        }
        return ss.toUpperCase();
    }

    /**
     * 将long型 十进制整数转为十六进制数，并补位
     */
    public static String longToHexString(long s) {
        String ss = Long.toHexString(s);
        if (ss.length() % 2 != 0) {
            ss = "0" + ss;//0F格式
        }
        return ss.toUpperCase();
    }

    public static void main(String[] args) {
        String aa = "9A000000009A94010076040000010007050010001000030000010003003020151005000100050010003000050002000500120000000000000000001a59864328fb1be0a0";
        System.out.println(longToHexString(18223704916L));
    }

    /**
     * 将二进制转换成十六进制串
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * int到byte[] 由高位到低位
     *
     * @param i 需要转换为byte数组的整行值。
     * @return byte数组
     */
    public static byte[] intToByteArray(int i) {
        byte[] result = new byte[4];
        result[0] = (byte) ((i >> 24) & 0xFF);
        result[1] = (byte) ((i >> 16) & 0xFF);
        result[2] = (byte) ((i >> 8) & 0xFF);
        result[3] = (byte) (i & 0xFF);
        return result;
    }

    /**
     * hex转int
     *
     * @param hex 需要转换成int
     * @return int值
     */
    public static int hexToInt(String hex) {
        return Integer.parseInt(hex, 16);
    }

    /**
     * byte[]转int
     *
     * @param bytes 需要转换成int的数组
     * @return int值
     */
    public static int byteArrayToInt(byte[] bytes) {
        int value = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (3 - i) * 8;
            value += (bytes[i] & 0xFF) << shift;
        }
        return value;
    }

    /*获取星期几*/
    public static String getWeek() {
        Calendar cal = Calendar.getInstance();
        int i = cal.get(Calendar.DAY_OF_WEEK);
        switch (i) {
            case 1:
                return "星期日";
            case 2:
                return "星期一";
            case 3:
                return "星期二";
            case 4:
                return "星期三";
            case 5:
                return "星期四";
            case 6:
                return "星期五";
            case 7:
                return "星期六";
            default:
                return "";
        }
    }

    public static String formatNum(int i) {
        DecimalFormat df = new DecimalFormat("00");
        return df.format(i);
    }


    public static String formatThree(int i) {
        DecimalFormat df = new DecimalFormat("000");
        return df.format(i);
    }

    /**
     * hex转int
     *
     * @param b 需要转换成int
     * @return int值
     */
    public static int hexToInt(byte b) {
        String hex = ("" + "0123456789ABCDEF".charAt(0xf & b >> 4) + "0123456789ABCDEF".charAt(b & 0xf));
        return Integer.parseInt(hex, 16);
    }


    /**
     * 筛选出字符串中的数字
     *
     * @param args
     * @return
     */
    public static String[] screenNum(String args) {
        //正则表达式，用于匹配非数字串，+号用于匹配出多个非数字串
        String regEx = "[^0-9]+";
        Pattern pattern = Pattern.compile(regEx);
        //用定义好的正则表达式拆分字符串，把字符串中的数字留出来
        String[] cs = deleteArray(pattern.split(args));
        return cs;
    }

    /**
     * 数字删除数组空白
     */
    public static String[] deleteArray(String[] strings) {
        List<String> tmp = new ArrayList<String>();
        for (String str : strings) {
            if (str != null && str.length() != 0) {
                tmp.add(str);
            }
        }
        return tmp.toArray(new String[0]);
    }

    /**
     * 从一个byte[]数组中截取一部分
     *
     * @param src
     * @param begin 数据开始值
     * @param count 数据字节长度
     * @return
     */
    public static byte[] subBytes(byte[] src, int begin, int count) {
        if (src.length < begin + count) {
            return null;
        }
        byte[] bs = new byte[count];
        for (int i = begin; i < begin + count; i++) {
            bs[i - begin] = src[i];
        }
        return bs;
    }

    /**
     * 求校验和
     *
     * @param data
     * @return
     */
    public static String makeChecksum(String data) {
        if (data == null || data.equals("")) {
            return "";
        }
        int total = 0;
        int len = data.length();
        int num = 0;
        while (num < len) {
            String s = data.substring(num, num + 2);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }

        int mod = total % 256;
        String hex = Integer.toHexString(mod);
        len = hex.length();
        // 如果不够校验位的长度，补0,这里用的是两位校验
        if (len < 2) {
            hex = "0" + hex;
        }
        return hex;
    }

    public static String subHexStrByByte(String hexStr, int start, int end) {
        return hexStr.substring(start * 2, end * 2);
    }

}
